package com.jiwei.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiwei.community.constants.SystemConstant;
import com.jiwei.community.dao.CommentMapper;
import com.jiwei.community.dao.UserMapper;
import com.jiwei.community.entity.Comment;
import com.jiwei.community.entity.User;
import com.jiwei.community.exception.SystemException;
import com.jiwei.community.service.CommentService;
import com.jiwei.community.service.PostService;
import com.jiwei.community.service.RecommendService;
import com.jiwei.community.service.UserService;
import com.jiwei.community.utils.BeanCopyUtils;
import com.jiwei.community.utils.RecommendUtils;
import com.jiwei.community.utils.SecurityUtils;
import com.jiwei.community.utils.SensitiveWordUtils;
import com.jiwei.community.vo.CommentVo;
import com.jiwei.community.vo.PageListVo;
import com.jiwei.community.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 评论表(Comment)表服务实现类
 *
 * @author 季伟
 * @since 2024-05-01 14:20:01
 */
@Service("commentService")
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    UserService userService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    PostService postService;
    RecommendService recommendService = new RecommendServiceImpl();
    @Override
    public ResponseResult publishComment(Comment comment) {
        if (comment.getFromType() == 0) {
            postService.updateCacheCommentNum(comment.getFromId(),1);
            try{
                Long userId = SecurityUtils.getUserId();
                if (userId != null && comment.getFromId()!=null && comment.getFromType() == 0 ){
                    updateScoreByComment(userId,comment.getFromId(),1);
                }
            }catch (SystemException ignore){

            }
        }else if (comment.getFromType() == 1){
            //TODO 增加动态的评论数值
        }
        save(comment);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getCommentTreeList(Integer fromType, Long fromId, Integer pageNum, Integer pageSize) {
        //创建条件构造器
        LambdaQueryWrapper<Comment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //如果是文章中的评论就按照文章id筛选，如果是友链中的评论就加这个条件
        lambdaQueryWrapper.eq(fromType!=null,Comment::getFromId,fromId);
        lambdaQueryWrapper.eq(fromType!=null,Comment::getFromType,fromType);
        //获取所有根评论
        lambdaQueryWrapper.eq(Comment::getRootId,-1);
        Page<Comment> page = new Page<>(pageNum,pageSize);
        page(page,lambdaQueryWrapper);
        List<Comment> commentList = page.getRecords();
        List<CommentVo> commentVos = transferToVoList(commentList);
        commentVos = commentVos.stream().peek(commentVo -> {
            commentVo.setContent(SensitiveWordUtils.replaceWord(commentVo.getContent()));//敏感词替换
            //查询每个根评论的子评论
            List<CommentVo> children = getChildren(commentVo.getId());
            commentVo.setChildren(children);
        }).collect(Collectors.toList());
        PageListVo<CommentVo> pageVo = new PageListVo<>(page.getTotal(),commentVos);
        return ResponseResult.okResult(pageVo);
    }
    /**
     * 根据根评论查询所有子评论
     * @param id 评论id
     * @return 子评论数组
     */
    private List<CommentVo> getChildren(Long id) {
        //TODO 优化为分页查询,以及参考b站实现多级评论
        LambdaQueryWrapper<Comment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Comment::getRootId,id);
        lambdaQueryWrapper.orderByAsc(Comment::getCreateAt);
        List<Comment> comments = list(lambdaQueryWrapper);
        return transferToVoList(comments);
    }

    /**
     * 将数据库关联评论对象添加一些页面中还要使用到的属性形成评论视图响应对象
     * @param comments 数据库查到的评论数组
     * @return 评论视图对象数组
     */
    private List<CommentVo> transferToVoList(List<Comment> comments){
        List<CommentVo> commentVoList = new ArrayList<>();
        for (Comment comment:comments){
            CommentVo commentVo = BeanCopyUtils.copyBean(comment,CommentVo.class);
            Long userId = comment.getCreateBy();
            if (userId == null || userId == -1L)continue;
            User creator = userMapper.getUserById(comment.getCreateBy());
            if (creator == null)continue;
            commentVo.setUsername(creator.getNickName());
            commentVo.setAvatar(creator.getAvatar());
            if (comment.getToCommentId() != -1 && comment.getToCommentId() != null){
                User replyTo = userMapper.getUserById(comment.getToCommentUserId());
                commentVo.setToCommentUserName(replyTo.getNickName());
            }
            commentVoList.add(commentVo);
        }
        return commentVoList;
    }


    public  void updateScoreByComment(Long userId, Long postId, Integer increase) {
        redisTemplate.opsForZSet().incrementScore(SystemConstant.REDIS_PREFIX_RECOMMEND_SCORE+userId,postId,SystemConstant.RECOMMEND_SCORE_FACTOR_COMMENT*increase);

    }



}

